﻿using Company.Core.Models;
using Company.Database.Base.Entities;
using Company.Database.Base.Repositories;
using Microsoft.AspNetCore.Mvc;

namespace Company.WebServer.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class DeviceController
    {
        private readonly ILogger<WeatherForecastController> _logger;
        private IHospitalRepository HospitalRepository { get; }
        private IDeviceRepository DeviceRepository { get; }
        public DeviceController(
            ILogger<WeatherForecastController> logger,
            IDeviceRepository deviceRepository,
            IHospitalRepository hospitalRepository)
        {
            DeviceRepository = deviceRepository;
            HospitalRepository = hospitalRepository;
            _logger = logger;
        }

        [HttpGet]
        [Route("GetDevices")]
        public async Task<IActionResult> GetDevices([FromQuery] int hospitalId, int stationId)
        {
            Result<List<DeviceEntity>> result = new();
            var entities = await DeviceRepository.GetAllAsync();
            if (entities == null || !entities.Any())
            {
                result.Success = false;
                result.Message = "没有数据";
                return new JsonResult(result);
            }
            entities = entities.FindAll(t => t.HospitalId == hospitalId && t.StationId == stationId);
            if (entities.Any())
            {
                result.Success = true;
                result.Message = "操作成功";
                result.Value = entities;
            }
            return new JsonResult(result);
        }

        /// <summary>
        /// 更新设备的连接信息
        /// </summary>
        /// <param name="device"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Update")]
        public async Task<IActionResult> Update(DeviceEntity device)
        {
            Result<DeviceEntity> result = new();
            if(device == null)
            {
                result.Success = false;
                result.Message = "没有数据";
                return new JsonResult(result);
            }

            //获取当前设备
            var entity = await DeviceRepository.GetByIdAsync(device.Id);
            if (entity == null)
            {
                result.Success = false;
                result.Message = "没有数据";
                return new JsonResult(result);
            }

            entity.Protocol= device.Protocol;
            entity.IpAddress = device.IpAddress;
            entity.Port = device.Port;
            entity.SerialName= device.SerialName;
            entity.BaudRate = device.BaudRate;
            entity.ClassName= device.ClassName;
            var success = await DeviceRepository.UpdateAsync(entity) > 0;
            if(success)
            {
                result.Success = true;
                result.Message = "操作成功";
                result.Value = entity;
            }
            return new JsonResult(result);
        }
    }
}
